package lsl.leetCode.year2023.test0203;

/**
 * description:
 *
 * @author: liushengli
 * data: 2023/2/3
 */
public class test53 {
    public static void main(String[] args) {
       /* int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 8;*/
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 2;
        System.out.println(search(nums, target));
    }

    public static int search(int[] nums, int target) {
        boolean lower = true;
        int leftIndex = searchRange(nums, target, lower);
        int rightIndex = searchRange(nums, target, false) - 1;
        //剑指 Offer 53 - I. 在排序数组中查找数字 I
        if (leftIndex <= rightIndex && rightIndex < nums.length && nums[leftIndex] == target && nums[rightIndex] == target) {
            return rightIndex - leftIndex + 1;
        }
        return 0;
    }

    public static int searchRange(int[] nums, int target, boolean lower) {
        int left = 0;
        int right = nums.length - 1;
        int ans = nums.length;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target || (lower && nums[mid] >= target)) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }

        }
        return ans;
    }
}
